package com.chhuang.huaao.thread;

import java.util.Date;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;

import com.chhuang.core.holder.SpringContextHolder;
import com.chhuang.huaao.handler.ServerHandler;
import com.chhuang.huaao.po.HaMachine;
import com.chhuang.huaao.service.IHaMachineService;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;

/**
 * 等待设备回复
 * @author CHHUANG
 *
 */
public class WaitThread implements Runnable {
	private static final Log log = LogFactory.getLog(WaitThread.class);
	
	private IHaMachineService machineService = SpringContextHolder.getBean("haMachineServiceImpl");
	
	/**
	 * 所有等待队列
	 */
	public static Set<String> waitSet = new CopyOnWriteArraySet<String>();
	
	private String machineId;
	
	private long heartTime;
	
	WaitThread(String machineId, long heartTime){
		this.machineId = machineId;
		this.heartTime = heartTime;
	}
	
	@Override
	public void run() {
		if(Assert.isInvalidString(machineId)){
			return ;
		}
		if(waitSet.contains(machineId)){//已存在
			return ;
		}else{
			waitSet.add(machineId);
		}
		
		try {
			long max = SysConfig.getLong(SysConstants.Config.MAX_WAIT_TIME, 10000);
			Thread.sleep(max);//20秒后
			
			HaMachine machine = machineService.findByPrimaryKey(machineId);
			if(machine!=null){
				long time = machine.getHeartTime()==null? 0 : machine.getHeartTime().getTime();
				if(time == heartTime){//20秒后，心跳时间没有变化 表示 离线
					log.debug(machine.getMachineNum()+"查询20秒后，没有上传状态，关闭连接");
					IoSession session = ServerHandler.sessionMap.get(machine.getMachineNum());
					if(session!=null){
						session.close(true);session=null;
					}
					//修改数据库在线状态
					machine.setMachineOnlineStatus(0);
					machine.setModifyTime(new Date());
					machineService.update(machine);
					
					//修改sessionMap
					ServerHandler.sessionMap.remove(machine.getMachineNum());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		waitSet.remove(machineId);//移除
	}

}
